# -*- coding: utf-8 -*-
from django.contrib import admin
from models import Subscription
from django.shortcuts import render_to_response
from django.core.mail import send_mail
from django.conf import settings
from django.contrib.admin.views.decorators import staff_member_required
from django.template import RequestContext

from news.models import News

# ignore AlreadyRegistered
try:    
    admin.site.register(Subscription)
except Exception:
    pass


from django import forms

class EmailForm(forms.Form):
    
    recipient = forms.EmailField(help_text="Email address to send to")
    cc_myself = forms.BooleanField(required=False,
                            help_text="Do you want to get a copy of this mail?")
    subject = forms.CharField(widget=forms.TextInput(attrs={'size':'80'}),
                              help_text="Email subject")
    
    message = forms.CharField(widget=forms.Textarea(attrs={'cols':'80',
                                                           'rows':'20'}),
                              help_text="Your Message")
    continue_editing = forms.BooleanField(required=False,
                            help_text="Continue editing after sending")
    
    

@staff_member_required
def sendmail(request):
    status = None
    if request.method == 'POST': # If the form has been submitted...
        form = EmailForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            subject = form.cleaned_data["subject"]
            to = [form.cleaned_data["recipient"]]
            cc_myself = form.cleaned_data["cc_myself"]
            message = form.cleaned_data["message"]
            from_ = settings.DEFAULT_FROM_EMAIL
            try:
                send_mail(subject, message, from_, to, fail_silently=False)
                if cc_myself:
                    send_mail(subject, message, from_, [request.user.email],
                              fail_silently=False)
                status = "success"
            except Exception, e:
                status = e
            if not form.cleaned_data["continue_editing"]:
                form = EmailForm()        

    else:
        form = EmailForm()
        if "news-id" in request.GET:
            try:
                news = News.objects.get(pk=request.GET["news-id"])
            except News.DoesNotExist:
                status = "News with id ``%i`` not found" % request.GET["news-id"]
            else:
                form = EmailForm(initial={"subject":news.title, 
                                          "message":news.content})
                
        

    return render_to_response('admin/sendmail.html', {
        'form': form, 'status': status,
    }, context_instance=RequestContext(request))
